
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "lib/time_period.h"
#include "doAction.h"

/**
 * @brief 发送控制指令到指定端口
 * @param pdPort_be  端口号（大端序）
 * @param data       指向32字节数据区的指针
 * @return 0成功，-1失败
 */
int doAction(uint16_t pdPort_be, uint8_t *data)
{
    int sockfd;
    struct sockaddr_in local_addr, dest_addr;

    // 从外部配置文件读取目的IP和端口
    char dest_ip[64] = {0};
    uint16_t dest_port = 0;
    FILE *fp = fopen("config.conf", "r");
    if (fp) {
        char line[128];
        while (fgets(line, sizeof(line), fp)) {
            if (sscanf(line, "dest_ip = %63s", dest_ip) == 1) {
                continue;
            }
            if (sscanf(line, "dest_port = %hu", &dest_port) == 1) {
                continue;
            }
        }
        fclose(fp);
    }
    // 如果配置文件未设置，则使用默认值
    if (dest_ip[0] == '\0') {
        strcpy(dest_ip, "192.168.0.200");
    }
    
    if (dest_port == 0) {
        dest_port = 8000;
    }

    // 创建UDP socket
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        return -1;
    }

    // 配置本地地址
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = inet_addr(LOCAL_IP);
    local_addr.sin_port = htons(0); // 系统自动分配端口

    if (bind(sockfd, (struct sockaddr*)&local_addr, sizeof(local_addr)) < 0) {
        perror("bind failed");
        close(sockfd);
        return -1;
    }

    // 配置目标地址
    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.sin_family = AF_INET;
    dest_addr.sin_addr.s_addr = inet_addr(dest_ip);
    dest_addr.sin_port = htons(dest_port);

    // 组装发送数据
    mvb_data_full send_data;
    memset(&send_data, 0, sizeof(send_data));
    send_data.TID = 0x21;      // 示例TID
    send_data.fcode = 0x04;    // 示例fcode
    send_data.pdPort = pdPort_be;

    if (data != NULL) {
        memcpy(send_data.pdData, data, sizeof(send_data.pdData));
    }
    
    // 发送数据
    ssize_t sent = sendto(sockfd, &send_data, sizeof(send_data), 0,
                          (struct sockaddr*)&dest_addr, sizeof(dest_addr));
    if (sent < 0) {
        perror("sendto failed");
        close(sockfd);
        return -1;
    }

    // 打印发送内容
    printf("doAction: 端口0x%04X, 已发送%zd字节到%s:%d\n",
           pdPort_be, sent, dest_ip, dest_port);

    close(sockfd);
    return 0;
}